package com.deerlive.jni;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.ImageFormat;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.deerlive.jni.ffmpeg.FFmpegHandle;
import com.deerlive.jni.utils.LogUtils;

import java.io.IOException;
import java.util.Calendar;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback, Camera.PreviewCallback{

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("avutil");
        System.loadLibrary("swresample");
        System.loadLibrary("avcodec");
        System.loadLibrary("avformat");
        System.loadLibrary("swscale");
        System.loadLibrary("avfilter");
        //System.loadLibrary("avdevice");
        //System.loadLibrary("postproc");
        System.loadLibrary("ffmpeg-handle");
    }

    private SurfaceView surfaceView;//预览摄像头
    private SurfaceHolder surfaceHolder;
    private Button button;//拍照按钮
    private Camera camera;//摄像头
    //private String url = "rtmp://pili-publish.sou001.com/kuailai/test";
    private String url = "http://pili-publish.sou001.com:1250/kuailai/123456782.httpts";
    //采集到每帧数据时间
    long previewTime = 0;
    //开始编码时间
    long encodeTime = 0;
    //采集数量
    int count = 0;
    //编码数量
    int encodeCount = 0;

    private final static int MAX_FPS = 25;
    private final static int FRAME_PERIOD = (1000 / MAX_FPS);
    long lastTime = 0;
    long timeDiff = 0;
    int framesSkipped = 0; // number of frames being skipped
    int framesRecevied = 0; // number of frames being skipped
    int framesSended = 0; // number of frames being skipped

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[] {Manifest.permission.CAMERA}, 1);
            }
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
            }
        }
        initView();
        initData();
        initListener();



    }

    //初始化View的方法,其实少的话都放到
    private void initView() {
        surfaceView = (SurfaceView) findViewById(R.id.main_surface_view);
        button = (Button) findViewById(R.id.main_button);
    }

    private void initData() {
        FFmpegHandle.init(this);
        FFmpegHandle.getInstance().initVideo(url);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
    }
    Boolean ifStartPush = false;
    private void initListener() {
        surfaceView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "surfaceView", Toast.LENGTH_SHORT).show();
            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               ifStartPush = !ifStartPush;
            }
        });
    }



    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        Log.i("====","surfaceCreated");
        try {
            // Camera,open() 默认返回的后置摄像头信息
            camera = Camera.open();//打开硬件摄像头，这里导包得时候一定要注意是android.hardware.Camera

            camera.setPreviewDisplay(surfaceHolder);//通过SurfaceView显示取景画面
            camera.setPreviewCallback(this);
            Camera.Parameters parameters = camera.getParameters();
            for (Camera.Size size : parameters.getSupportedPictureSizes()) {
                LogUtils.d(size.width + "  " + size.height);
            }

            parameters.setPreviewSize(640, 480);
            parameters.setPreviewFormat(ImageFormat.NV21);
            parameters.setPictureSize(640, 480);
            //parameters.setRotation(90);
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
            camera.setParameters(parameters);
            camera.startPreview();//开始预览
            camera.setDisplayOrientation(90);
        } catch (IOException e) {
            Log.e("====", e.toString());
        }
    }
    long startTime ;
    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        Log.i("====","surfaceChanged");
        startTime  =   System.currentTimeMillis();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.i("====","surfaceDestroyed");
        if (null != camera) {
            camera.setPreviewCallback(null);
            camera.stopPreview();
            camera.release();
            camera = null;
        }
    }
    ExecutorService executor = Executors.newSingleThreadExecutor();
    @Override
    public void onPreviewFrame(final byte[] data, Camera camera) {
        timeDiff = System.currentTimeMillis() - lastTime;
        if (timeDiff < FRAME_PERIOD){
            return;
        }

        executor.execute(new Runnable() {
            @Override
            public void run() {
                if(ifStartPush){
                    encodeTime = System.currentTimeMillis();
                    FFmpegHandle.getInstance().onFrameCallback(data);
                    LogUtils.w("编码第:" + (encodeCount++) + "帧，耗时:" + (System.currentTimeMillis() - encodeTime));
                }
            }
        });
        lastTime = System.currentTimeMillis();
    }
}
